package controller;

//import model.Board;
import model.ChessGame;
import model.Player;
import model.Square;
import graphics.Board2DView;
import graphics.Board3DView;
import graphics.interfaces.IGameView;
import graphics.view2D.Coord2D;

public class GameController {
	private IGameView boardView;
	private ChessGame chessGame;

	public GameController() {
		chessGame = new ChessGame();
		chessGame.initGame();
		
		// Using 2D board
		boardView = new Board2DView();
		// Using 3D board
		//boardView = new Board3DView();
		
		boardView.Load(this, chessGame);
	}

	/**
	 * Update of the game view parameters
	 */
	public void Update() {
		// game main loop
		Player currentPlayer = chessGame.getCurrentPlayer();
		if(currentPlayer.isMachine()){
			try {
				currentPlayer.playAsMachine(chessGame.getBoard());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} // else human action is triggered by MouseProcessor

	}

	/**
	 * Draw the game
	 */
	public void Draw() {
		boardView.Draw();
	}

	/*
	 * La vue nous notifie d'un clique sur le plateau par le joueur
	 */
	public void touchDown(int x, int y, int pointer, int button) {
		int col = Coord2D.getInstance().getColFromXY(x, y);
		int row = Coord2D.getInstance().getRowFromXY(x, y);
		Square square = Square.get(col, row);

		if (chessGame.getCurrentPlayer().isHuman()) {
			if (chessGame.isPiecePlayable(square)) {
				
				boardView.SelectSquare(square);
			} else {
				boardView.UnselectSquare();
			}
			chessGame.HumanPlayerAction(square);
		}
	}
}
